package Dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
//抽取一个DBGet工具类
//保证工具类的通用性 配置文件properties
public class DBGet {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    /*静态代码块 只需要读取一次就可以拿到这些值*/
    static {


        //加载文件
        try {
            //创建Properties集合类
            Properties pro = new Properties();
//            第一个方法
           // pro.load(new FileReader("src/utils/JDBC.properties"));
//            第二个方法
            //获取src路径下文件方式 ClassLoader类加载器
//            ClassLoader classLoader = JDBCutils.class.getClassLoader();
//            URL res = classLoader.getResource("JDBC.properties");
//            String path= res.getPath();
//            System.out.println(path);
//            pro.load(new FileReader(path));
//            等同
            InputStream inputStream = DBGet.class.getClassLoader().getResourceAsStream("Dao/JDBC.properties");
            pro.load(inputStream);

            url = pro.getProperty("url");
            password =pro.getProperty("password");
            user = pro.getProperty("user");
            driver = pro.getProperty("driver");
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }

    public static void close(Statement stmt, Connection conn) {
      close(stmt);
      close(conn);
    }
    /*
    重载方法
     */
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        close(rs);
        close(stmt);
        close(conn);
    }
    public static void close(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
